package base.utils

import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.PointF
import android.view.View
import android.widget.ImageView
import base.utils.BezierEvaluator

/**
 * @author njmsir
 * Created by njmsir on 2017/11/15.
 */
class AddCartAnimator {
    companion object {
        fun initBezier(view: View, context: Context, parentView: View, cart: View, bezierView: ImageView): ValueAnimator {
            //        二、计算动画开始/结束点的坐标的准备工作
            //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
            val parentLocation = IntArray(2)
            parentView.getLocationInWindow(parentLocation)
            //得到商品图片的坐标（用于计算动画开始的坐标）
            val startLoc = IntArray(2)
            view.getLocationInWindow(startLoc)
            //得到购物车图片的坐标(用于计算动画结束后的坐标)
            val endLoc = IntArray(2)
            cart.getLocationInWindow(endLoc)
            //        三、正式开始计算动画开始/结束的坐标
            //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
            val startX = (startLoc[0] + (view.measuredWidth / 2 - bezierView.measuredWidth / 2)).toFloat()
            val startY = (startLoc[1] + (view.measuredHeight - bezierView.measuredHeight) / 6).toFloat()
            //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
            val toX = (endLoc[0] - parentLocation[0] + cart.width / 5).toFloat()
            val toY = (endLoc[1] - parentLocation[1]).toFloat()

            val pointBezier = PointF(startX + (toX - startX) / 3, startY - view.height / 2)
            val pointStart = PointF(startX, startY)
            val pointEnd = PointF(toX, toY)
            val mValueAnimator = ValueAnimator.ofObject(BezierEvaluator(pointBezier.x, pointBezier.y), pointStart, pointEnd)
            mValueAnimator.duration = 1000
            mValueAnimator.addUpdateListener { animation ->
                val pointF = animation.animatedValue as PointF
                bezierView.visibility = View.VISIBLE
                bezierView.x = pointF.x
                bezierView.y = pointF.y
            }
            mValueAnimator.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {

                }

                override fun onAnimationEnd(animation: Animator) {
                    bezierView.visibility = View.GONE
                }

                override fun onAnimationCancel(animation: Animator) {

                }

                override fun onAnimationRepeat(animation: Animator) {

                }
            })
            mValueAnimator.setTarget(bezierView)
            mValueAnimator.repeatCount = 0
            mValueAnimator.repeatMode = ValueAnimator.REVERSE
            return mValueAnimator
        }
    }
}